package jinyilw.swing.visuals.label;

import jinyilw.common.Operator;

import javax.swing.Icon;
import javax.swing.JLabel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

/**
 * @author Jinyi
 */
public class ActionLabel extends JLabel// 响应式图像标签
{
	private static final long serialVersionUID = 8531824112488923592L;
	private Icon icon;
	private Icon overIcon;
	private OverListener listener;
	private volatile ArrayList<Operator<MouseEvent>> operators;

	public ActionLabel()
	{
	}

	public ActionLabel(Icon icon, Icon oic)
	{
		setActionIcon(icon, oic);
	}

	//	public ActionLabel(String iconPath, String oicPath)
	//	{
	//		setResActionIcon(iconPath, oicPath);
	//	}

	private synchronized void createOperators()
	{
		if (operators == null)
		{
			operators = new ArrayList<>();
			addMouseListener(new MouseAdapter()
			{
				@Override
				public void mouseClicked(MouseEvent e)
				{
					if (isEnabled())
						for (Operator<MouseEvent> operator : operators)
							operator.operate(e);
				}
			});
		}
	}

	public void addClickOperator(Operator<MouseEvent> operator)
	{
		if (operators == null)
			createOperators();
		operators.add(operator);
	}

	//	public void setResActionIcon(String iconPath, String oicPath)
	//	{
	//		setActionIcon(ResourceManager.getResLazyScaleIcon(iconPath),
	//				ResourceManager.getResLazyScaleIcon(oicPath));
	//	}

	public void setActionIcon(Icon ic, Icon oic)
	{
		icon = ic;
		setIcon(ic);
		overIcon = oic;
		if (listener == null)
		{
			listener = new OverListener();
			addMouseListener(listener);
		}
	}

	//	@Override
	//	public void updateUI()
	//	{
	//		setUI(new BasicLabelUI());
	//	}

	private class OverListener extends MouseAdapter
	{
		@Override
		public void mouseEntered(MouseEvent e)
		{
			if (isEnabled() && overIcon != null)
				setIcon(overIcon);
		}

		@Override
		public void mouseExited(MouseEvent e)
		{
			if (isEnabled() && icon != null)
				setIcon(icon);
		}
	}
}
